<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExport2Excel">excel导出</el-button>
          <el-button v-allow="'add_employees'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList" :default-sort="{prop: 'workNumber', order: 'ascending'}">
          <el-table-column label="序号" type="index" :index="qaq" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default=" { row }">
              {{ formatEmployment(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="150">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 8, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <add-or-edit v-if="showDialog" ref="addoredit" @hClose="hCancel" @hSuccess="hAdd" />
      </el-dialog>
      <!-- 实现分配角色的弹层 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showRoleDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <AssignRole v-if="showRoleDialog" :cur-id="curId" @hClose="showRoleDialog=false;$message.info('已取消操作')" @success="hRoleSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import AssignRole from '@/views/employees/assignRole.vue'
// const hireType = {}
// EmployeeEnum.hireType.forEach((item) => (hireType[item.id] = item.value))
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
const hireTypEnmu = { 1: '正式', 2: '非正式' }

import addOrEdit from './empDialog'
export default {
  name: 'Employees',
  components: {
    addOrEdit,
    AssignRole
  },
  data() {
    return {
      page: 1, // 页面
      size: 10, // 每页条数
      employeesList: [], // 员工列表
      total: 0,
      showDialog: false,
      showRoleDialog: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    hRoleSuccess(q) {
      this.showRoleDialog = false
      this.loadEmployeesList()
      this.$message.success(q)
    },
    hAssignRole(id) {
      this.showRoleDialog = true
      console.log(id)
      this.curId = id
    },
    async hExport2Excel() {
      // 1. 发送请求,拿到真实的数据
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        console.log(res)
        const list = res.data.rows
        // 2. 将拿到的数据进行格式化操作
        const { header, data } = this.formatData(list)
        console.log(header, data)
        // 3. 将格式化之后的数据转化为excel表格
        import('@/vendor/Export2Excel').then((excel) => {
          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: 'qwq',
            autoWidth: true,
            bookType: 'xlsx'
          })
          this.downloadLoading = false
        })
      } catch (error) {
        console.log(error)
      }
    },
    formatData(list) {
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      let header = [] // 表头
      let data = [] // 表数据
      const one = list[0]
      if (!one) return { header, data }
      console.log(Object.keys(one))
      header = Object.keys(one).map((item) => mapInfo[item])
      data = list.map((ele) => {
        ele.formOfEmployment = hireTypEnmu[ele.formOfEmployment] || '未知' // 1,2
        return Object.values(ele)
      })
      return { header, data }
    },
    hAdd(val) {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeesList()
      this.$message.success(val)
    },
    hCancel() {
      this.showDialog = false
      this.$message.info('已取消操作')
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('删除员工', res)
        if (this.employeesList.length === 1) this.page--
        if (this.page <= 0) this.page = 1
        this.loadEmployeesList()
        this.$message.success(res.message)
        // 保存数据
      } catch (err) {
        console.log('删除员工', err)
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {
          this.$message.info('已取消操作')
        })
    },
    // 获取员工列表
    async loadEmployeesList() {
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        console.log(res)
        this.employeesList = res.data.rows
        this.employeesList.forEach(
          (item) => (item.timeOfEntry = item.timeOfEntry.split('T')[0])
        )
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 后端传过来的数据,自己进行处理
    formatEmployment(num) {
      // 从hireType中 通过id找到对应的元素的value
      // const item = EmployeeEnum.hireType.find((it) => it.id === num)
      // return item ? item.value : '未知'
      return hireType[num]
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    },
    qaq(index) {
      return (this.page - 1) * this.size + index + 1
    }
  }
}
</script>
